# coding: utf-8

from xml.etree.ElementTree import ElementTree, Element

class DynetRender(object):
    def __init__(self, meta):
        self.meta = meta
        self.nodelist = []
        self.networksdict = {}


        self.root = Element('DynamicNetwork')
        metaMat = Element('MetaMatrix')
        nodesroot = Element('nodes')
        self.networks = Element('networks')

        self.root.append(metaMat)
        metaMat.append(nodesroot)
        metaMat.append(self.networks)

        self.nodes = Element('nodeset', id='units', type='resource')
        nodesroot.append(self.nodes)

    def get_graph(self, name):
        n = self.networksdict.get(name)
        if n:
            return n
        else:
            n = Element('graph',
                        id=name,
                        targetType='resource',
                        sourceType='resource',
                        isDirected='true')
            self.networks.append(n)
            self.networksdict[name] = n
            return n

    def add_nodes(self, ref):
        self.add_node(ref.name)
        for refs in ref.targets.values():
            for name in refs:
                self.add_node(name)

    def add_node(self, name):
        if name in self.nodelist:
            return
        self.nodes.append( Element('node', id=name) )
        self.nodelist.append(name)

    def add_edges(self, graph, source, dests):
        for d in dests:
            e = Element('edge',
                        source=source,
                        target=d,
                        type='binary',
                        value='1')
            graph.append(e)

    def render(self, f):

        for ref in self.meta.references:
            self.add_nodes(ref)
            for name, dests in ref.targets.items():
                g = self.get_graph(name)
                self.add_edges(g, ref.name, dests)


        ElementTree(self.root).write(f)